<template>
  <div class="app-container">
    <el-drawer :title="title" :visible.sync="openDetail" size="80%" @close="cancel">
      <template v-slot:title>
        <span class="titleDiv">{{ title }}</span>
      </template>
      <div style="padding: 0 20px">
        <div>
          <el-form ref="requisitionForm" :model="requisitionForm" label-width="100px">
            <el-row>
              <el-col :span="8">
                <el-form-item label="工单编号" prop="workorderCode">
                  <el-input v-model="requisitionForm.workorderCode" placeholder="请输入工单编号" disabled />
                </el-form-item>
              </el-col>
              <el-col :span="8">
                <el-form-item label="工单数量" prop="quantity">
                  <el-input v-model="requisitionForm.quantity" placeholder="请输入生产数量" disabled />
                </el-form-item>
              </el-col>
              <el-col :span="8">
                <el-form-item label="批次号" prop="batchName">
                  <el-input v-model="requisitionForm.batchName" placeholder="请输入批次号" disabled />
                </el-form-item>
              </el-col>
            </el-row>
            <el-row>
              <el-col :span="8">
                <el-form-item label="产品编号" prop="productCode">
                  <el-input v-model="requisitionForm.productCode" placeholder="请选择产品" disabled></el-input>
                </el-form-item>
              </el-col>
              <el-col :span="8">
                <el-form-item label="产品名称" prop="productName">
                  <el-input v-model="requisitionForm.productName" placeholder="请选择产品" disabled />
                </el-form-item>
              </el-col>
              <el-col :span="8">
                <el-form-item label="规格型号" prop="productSpc">
                  <el-input v-model="requisitionForm.productSpc" placeholder="请选择产品" disabled />
                </el-form-item>
              </el-col>
            </el-row>
          </el-form>

          <el-table v-loading="loading" :data="workorderDataList" default-expand-all height="73vh">
            <el-table-column type="index" width="50" label="序号"></el-table-column>

            <el-table-column label="物料编号" width="130" align="center" prop="itemCode" />
            <el-table-column label="物料名称" width="130" align="center" prop="itemName" :show-overflow-tooltip="true" />
            <el-table-column label="规格型号" width="260" align="center" prop="specification"
              :show-overflow-tooltip="true" />
            <el-table-column v-if="form.id == null" label="用量:分子" align="center" prop="jdyNumerator">
            </el-table-column>

            <el-table-column label="领料仓库" align="center" prop="bdInventoryList" width="130">
              <template slot-scope="scope">
                <div>
                  <el-select v-model="scope.row.fstockName" placeholder="请选择领料仓库" :key="scope.row.itemCode"
                    style="width: 120px" @change="(e) => fstockChage(e, scope.row, scope.$index)">
                    <el-option v-for="item in scope.row.bdInventoryList" :key="item.fstockId + scope.row.itemCode"
                      :label="item.fstockName" :value="item.fstockName"></el-option>
                  </el-select>
                </div>
              </template>
            </el-table-column>

            <el-table-column label="批次号" align="center" prop="proFlotInfoDtoList" width="130">
              <template slot-scope="scope">
                <el-input style="width: 120px" v-model="scope.row.attr1" :controls="false"
                  @focus="(e) => serialQuery(e, scope.row, scope.$index)"></el-input>
              </template>
            </el-table-column>

            <el-table-column label="库存量" align="center" prop="fbaseQty" width="90"></el-table-column>

            <el-table-column label="实发数量" align="center" prop="payableQty" width="90"></el-table-column>

            <el-table-column label="已领数量" align="center" prop="receivedQty" width="90"></el-table-column>

            <el-table-column label="领料数量" align="center" prop="productNum" width="130">
              <!-- <template slot-scope="scope">
                <el-input
                  style="width: 120px"
                  v-model="scope.row.productNum"
                  :controls="false"
                ></el-input>
              </template> -->
            </el-table-column>
            <el-table-column label="单位" align="center" prop="unitOfMeasure" />
            <el-table-column label="用量:分母" width="90px" align="center" prop="jdyDenominator" v-if="form.id == null">
              <template slot-scope="scope">
                <span>
                  {{ scope.row.jdyDenominator ? scope.row.jdyDenominator : 1 }}
                </span>
              </template>
            </el-table-column>
            <el-table-column v-if="form.id == null" label="所属工序" width="100" align="center" prop="processName" />
          </el-table>

          <!-- 选择批次号 -->
          <el-dialog title="选择批次号" :visible.sync="open" width="1000px" :append-to-body="true">
            <!-- height="550px" -->
            <el-table :data="batchList" @selection-change="handleSelectionChange">
              <el-table-column type="selection" width="55" align="center" />
              <el-table-column prop="flot" width="180" label="批号ID" align="center"></el-table-column>
              <el-table-column prop="lotName" width="180" label="批号名称" align="center"></el-table-column>
              <el-table-column prop="storageTime" width="200" label="入库时间" align="center"></el-table-column>
              <el-table-column prop="baseQty" width="150" label="库存数量" align="center"></el-table-column>
              <el-table-column prop="quantityIssued" width="150" label="领料数量" align="center">
                <template slot-scope="scope">
                  <el-input-number style="width: 120px" v-model="scope.row.quantityIssued"
                    :controls="false"></el-input-number>
                </template>
              </el-table-column>
            </el-table>

            <div style="display: flex; justify-content: center; align-items: center; margin-top: 10px;">
              <el-button type="success" @click="determine">确定</el-button>
              <el-button type="info" @click="open = false;">取消</el-button>
            </div>
            <!--            <el-button type="success" @click="determine">确 定</el-button>-->
          </el-dialog>

          <div slot="footer" class="dialog-footer">
            <!--        <el-button type="primary" @click="cancel" v-if="optType == 'view' || form.status != 0">返回</el-button>-->
            <el-button type="primary" @click="handleProductRequisition">保 存</el-button>
            <el-button @click="cancel">取 消</el-button>
          </div>
        </div>
      </div>
    </el-drawer>
  </div>
</template>

<script>
import { getWorkorder, getSerialList } from "@/api/mes/pro/workorder";
import { proBOMList, getBOMList } from "@/api/mes/md/bom";
import { addIssueheader } from "@/api/mes/wm/issueheader";
export default {
  data() {
    return {
      openDetail: false,
      title: "生成领料单",
      // 是否显示弹出层
      open: false,
      //序列号list
      workorderSnList: [],
      // 表单参数
      form: {},
      requisitionForm: {},
      loading: false,
      routeproductbomList: [],
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        workorderCode: null,
        workorderId: null,
        workorderName: null,
        orderSource: null,
        sourceCode: null,
        productId: null,
        productCode: null,
        productName: null,
        productSpc: null,
        unitOfMeasure: null,
        quantity: null,
        quantityProduced: null,
        quantityChanged: null,
        quantityScheduled: null,
        clientId: null,
        clientCode: null,
        clientName: null,
        requestDate: null,
        parentId: null,
        ancestors: null,
        status: null,
      },
      productRequisitionData: {},
      workorderDataList: [],
      //批次号list
      batchList: [],
      //选择批次号数据的index
      batchIndex: "",
      // 选择的 批次号数组
      selectionList: [],
    };
  },
  methods: {
    //初始化函数
    init(row) {
      console.log(row, "子组件的row");
      this.form = row;
      //调接口需要的id
      this.workorderId = row.workorderId;
      this.openDetail = true;
      this.getList();
    },
    getList() {
      this.loading = true;
      getWorkorder(this.form.workorderId).then((response) => {
        this.requisitionForm = response.data;
        if (this.form.id != null) {
          this.requisitionForm.isIssue = this.form.isIssue;
        }
        this.openRequisition = true;
        this.title = "生成领料单";
        this.optType = "edit";
        this.warehouseList = response.warehouseList || [];
        this.queryParams.productId = this.requisitionForm.productId;
        this.queryParams.workorderId = this.form.workorderId;
        this.queryParams.workorderQuantity = this.requisitionForm.quantity;
        this.queryParams.supplyId = this.form.id;
        this.productRequisitionData = this.requisitionForm;
        // 获取领料数量
        // getReceivedNumByWorkorderId(row.workorderId).then((response) => {
        //   this.requisitionForm.receivedNum = response.data;
        //   Vue.set(this.requisitionForm, "receivedNum", response.data);
        // });
        if (this.form.id != null) {
          getBOMList(this.queryParams).then((res) => {
            console.info("response", res);
            for (var i = 0; i < res.data.length; i++) {
              res.data[i].productNumMax = res.data[i].remainingQuantity;
              // res.data[i].productNum = res.data[i].productNum || 0;
              res.data[i].fbaseQty = res.data[i].fbaseQty || 0;
            }
            this.workorderDataList = res.data;
            console.log(
              this.workorderDataList,
              "======this.workorderDataList ======"
            );
            this.loading = false;
            this.getSpanArr(res.data || []);
            this.productRequisitionData.mdProductBomList =
              this.workorderDataList;
          }).catch(() => {
            this.loading = false;
          });
        } else {
          proBOMList(this.queryParams).then((res) => {
            console.info("response", res);
            for (var i = 0; i < res.data.length; i++) {
              res.data[i].productNumMax = res.data[i].remainingQuantity;
              // res.data[i].productNum = res.data[i].remainingQuantity;
              res.data[i].fbaseQty = res.data[i].fbaseQty || 0;
            }
            this.workorderDataList = res.data;
            console.log(
              this.workorderDataList,
              "======this.workorderDataList ======"
            );
            this.loading = false;
            this.getSpanArr(res.data || []);
            this.productRequisitionData.mdProductBomList =
              this.workorderDataList;
          }).catch(() => {
            this.loading = false;
          });
        }

        // routeBOMList(this.queryParams).then(response => {
        //   console.log('response.rows====bom====>222', response)
        //   this.workorderDataList = response.rows;
        //   this.total = response.total;
        //   this.loading = false;
        //   // this.productRequisitionData = {...this.requisitionForm};
        //   this.productRequisitionData = this.requisitionForm;

        // });
      });
    },
    // 取消按钮
    cancel() {
      this.openDetail = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        workorderId: null,
        workorderCode: null,
        workorderName: null,
        orderSource: null,
        sourceCode: null,
        productId: null,
        productCode: null,
        productName: null,
        productSpc: null,
        unitOfMeasure: null,
        quantity: null,
        quantityProduced: null,
        quantityChanged: null,
        quantityScheduled: null,
        clientId: null,
        clientCode: null,
        clientName: null,
        requestDate: null,
        parentId: null,
        status: 0,
        remark: null,
        createBy: null,
        createTime: null,
        updateBy: null,
        updateTime: null,
        orderType: null,
        fPlanStartDate: null,
        fPlanFinishDate: null,
      };
      this.autoGenFlag = false;
      this.resetForm("form");
    },

    // 行合并
    objectSpanMethod({ row, column, rowIndex, columnIndex }) {
      if (columnIndex === 1) {
        const _row = this.spanArr[rowIndex]; // 合并行数
        const _col = this.spanArr[rowIndex] > 0 ? 1 : 0; // 合并的列数
        return {
          rowspan: _row,
          colspan: _col,
        };
      }
    },
    // 按照类型合并
    getSpanArr(data) {
      this.spanArr = []; // tip: 后台获取完成数据后，一定要重置spanArr=[],避免出现合并混乱！！！！！
      if (data.length > 0) {
        for (let i = 0; i < data.length; i++) {
          // 当为第一行时
          if (i === 0) {
            this.spanArr.push(1);
            this.pos = 0;
          } else {
            // 判断当前值是否与上一行的【名称】相等，相等则进行合并
            if (data[i].processName === data[i - 1].processName) {
              this.spanArr[this.pos] += 1; // 合并单元格：合并的行数 +1
              this.spanArr.push(0); // 0代表单元格是不需要显示, 已经被合并的单元格
            } else {
              this.spanArr.push(1); // 1代表当前这行的数据需要被显示
              this.pos = i;
            }
          }
        }
      }
    },

    // 领料仓库修改  仓库选择的cahnge事件
    fstockChage(value, obj, index) {
      console.log(value, obj, index, "====value,obj,index======-");
      //给领料仓库赋值 
      this.workorderDataList[index].fstockName = value;
      // 清除领料数量
      this.workorderDataList[index].productNum = 0;
      // 清除批次号
      this.workorderDataList[index].attr1 = null;
      this.workorderDataList[index].fbaseQty =
        obj.bdInventoryList.filter((_) => _.fstockName == value)[0]?.fbaseQty ||
        0;
      this.productRequisitionData.mdProductBomList = this.workorderDataList;

      obj.bdInventoryList.forEach((item) => {
        if (item.fstockName == value) {
          obj.proFlotInfoDtoList = item.proFlotInfoDtoList;
        }
      });
    },
    //批次号 focus事件
    serialQuery(value, obj, index) {
      this.open = true;
      console.log(value, "value");
      console.log(obj, "obj");
      console.log(index, "index");
      //保存选择批次号数据的index
      this.batchIndex = index;
      this.batchList = obj.proFlotInfoDtoList;
      console.log(this.batchList, "batchList");
      // let param = {
      //   batch: obj.attr1,
      //   itemCode: obj.itemCode,
      //   itemId: obj.itemId,
      //   itemName: obj.itemName,
      //   workorderId: obj.workorderId,
      // };
      // getSerialList(param).then((res) => {
      //   console.log(res, "序列号查询的res");
      //   if (res.code == 200) {
      //     this.workorderSnList = res.data;
      //     this.index = index;
      //   }
      // });
      // if (obj.attr2 !== null) {
      //   this.serialList = obj.attr2.split(",");
      //   for (let i = 0; i < this.serialList.length; i++) {
      //     for (let n = 0; n < this.workorderSnList.length; n++) {
      //       if (this.serialList[i] == this.workorderSnList[n].serialNumber) {
      //         this.workorderSnList[n].checked = true;
      //       }
      //     }
      //   }
      // }
    },
    //批次号的change事件
    handleSelectionChange(selection) {
      console.log(selection, "selection");
      this.selectionList = selection;
    },
    //批次号选完之后 确定事件
    determine() {
      //库存数量
      let baseQty = 0;
      //领料数量
      let quantityIssued = 0;
      for (let i = 0; i < this.selectionList.length; i++) {
        // 单行 不允许 领料数量大于库存数量
        if (this.selectionList[i].quantityIssued > this.selectionList[i].baseQty) {
          this.$modal.msgError("领料数量不能大于库存数量")
          return
        }
        //把选好的库存数量累加起来赋值给外层的库存数量
        baseQty += this.selectionList[i].baseQty;
        //把选好的领料数量累加起来赋值给外层的领料数量
        quantityIssued += this.selectionList[i].quantityIssued;
        for (let j = 0; j < this.workorderDataList[this.batchIndex].proFlotInfoDtoList.length; j++) {
          if (this.selectionList[i].flot === this.workorderDataList[this.batchIndex].proFlotInfoDtoList[j].flot) {
            this.workorderDataList[this.batchIndex].proFlotInfoDtoList[j] = this.selectionList[i];
            break; // 找到匹配项后跳出内层循环
          }
        }
      }
      // 累加不允许 领料数量大于实发数量
      if (quantityIssued > this.workorderDataList[this.batchIndex].payableQty) {
        this.$modal.msgError("领料数量不能大于实发数量")
        return
      }
      // 使用map方法提取每个对象的flot属性
      let flotArray = this.selectionList.map((item) => item.flot);
      this.workorderDataList[this.batchIndex].fbaseQty = baseQty;

      this.workorderDataList[this.batchIndex].productNum = quantityIssued || 0
      this.workorderDataList[this.batchIndex].attr1 = flotArray.join(", ");

      console.log(this.workorderDataList[this.batchIndex], "...selection");

      this.open = false;
    },
    // 领料单
    handleProductRequisition() {
      let list = this.productRequisitionData.mdProductBomList;
      let greaterList = []; //实际领料数 大于 库存量
      let maxList = []; //实际领料数小于 需要领料数
      if (list && list.length > 0) {
        for (let i = 0; i < list.length; i++) {
          list[i].warehouseName = list[i].fstockName;
          list[i].productNum = list[i].productNum || 0
          // list[i].productNum = (this.productRequisitionData.quantity * list[i].jdyNumerator).toFixed(2)
          // productNumMax  fbaseQty
          if (list[i].productNum > list[i].fbaseQty) {
            greaterList.push(list[i]);
          }
          if (
            list[i].productNum < list[i].productNumMax &&
            list[i].productNum <= list[i].fbaseQty
          ) {
            maxList.push(list[i]);
          }
        }
      }
      // 领料数小于库存量  判断  先注释掉
      if (greaterList && greaterList.length > 0) {
        let str = "";
        console.log(greaterList, "=====greaterList=======");
        for (let i = 0; i < greaterList.length; i++) {
          str += `
                  <div >物料编号：${greaterList[i].itemCode}  物料名称：${greaterList[i].itemName} 领料数量：${greaterList[i].productNum} 库存数量：${greaterList[i].fbaseQty} 未完全领出</div>
                `;
        }
        return this.$message({
          dangerouslyUseHTMLString: true,
          message: str,
          type: "error",
          // duration:5,
        });
      }
      let strMax = "";
      if (maxList && maxList.length > 0) {
        console.log(maxList, "=====greaterList=======");
        for (let i = 0; i < maxList.length; i++) {
          strMax += `
              <div>物料编号：${maxList[i].itemCode}  物料名称：${maxList[i].itemName} 领料数量：${maxList[i].productNum} 库存数量：${maxList[i].fbaseQty} 未完全领出</div>
             `;
        }
      }
      strMax += `<div><i class="el-icon-warning" style='color:#ffba00;font-size: 24px '></i>是否确认保存 !!!</div>`;
      this.$confirm(`${strMax}`, {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        dangerouslyUseHTMLString: true,
        customClass: "confirm",
        title: "系统提示",
      })
        .then(() => {
          let obj =
            this.warehouseList.filter(
              (_) =>
                _.jdyWarehouseId == this.productRequisitionData.jdyWarehouseId
            ) || [];
          this.productRequisitionData.wareHouse =
            obj && obj.length > 0 ? obj[0] : {};
          this.$set(this.productRequisitionData, "supplyId", this.form.id);
          // let list = this.productRequisitionData.mdProductBomList;
          // if (list && list.length > 0) {
          //   for (let i = 0; i < list.length; i++) {
          //     list[i].warehouseName = list[i].fstockName;
          //     list[i].productNum = (this.productRequisitionData.quantity * list[i].jdyNumerator).toFixed(2);
          //   }
          // }
          // this.productRequisitionData.mdProductBomList = list;
          console.log(
            this.productRequisitionData,
            "=====this.productRequisitionData======"
          );
          this.$refs["requisitionForm"].validate((valid, value) => {
            if (valid) {
              addIssueheader(this.productRequisitionData).then((response) => {
                if (response.recordsList && response.recordsList.length > 0) {
                  let str = ` <div><p>以下物料库存没有:</p> `;
                  for (let i = 0; i < response.recordsList.length; i++) {
                    str += ` <div >${response.recordsList[i]}</div> `;
                  }
                  // style=" line-height: 26px;"
                  str += `</div>`;
                  this.$message({
                    dangerouslyUseHTMLString: true,
                    message: str,
                    type: "error",
                    // duration:5,
                  });
                } else if (response.infoList && response.infoList.length > 0) {
                  let str = ` <div><p>以下物料库存不足:</p> `;
                  for (let i = 0; i < response.recordsList.length; i++) {
                    str += ` <div >${response.recordsList[i]}</div>`;
                  }
                  // style=" line-height: 26px;"
                  str += `</div>`;
                  this.$message({
                    dangerouslyUseHTMLString: true,
                    message: str,
                    type: "error",
                    // duration:5,
                  });
                } else {
                  this.$modal.msgSuccess("新增成功");
                }

                this.openDetail = false;
                this.$emit("getList");
                // this.getList();
              });
            } else {
            }
          });
        })
        .catch(() => { });
    },
  },
};
</script>
<style rel="stylesheet/scss" lang="scss" scoped>
.app-container ::v-deep .el-drawer__header {
  padding-top: 10px !important;
  padding-bottom: 5px !important;
  margin-bottom: 10px !important;
}

.dialog-footer {
  padding-top: 10px;
  text-align: right;
}
</style>
<style>
.confirm {
  max-height: 70vh;
}

.titleDiv {
  font-weight: 700 !important;
  font-size: 20px;
}
</style>
